/*
 * Copyright (c) 2018-2999 广州亚米信息科技有限公司 All rights reserved.
 *
 * https://www.gz-yami.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */

package com.yami.shop.api.controller;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yami.shop.bean.model.User;
import com.yami.shop.bean.model.UserLabel;
import com.yami.shop.bean.model.VipPackage;
import com.yami.shop.bean.param.VipBuyParam;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.dao.UserMapper;
import com.yami.shop.dao.VipPackageMapper;
import com.yami.shop.security.util.SecurityUtils;
import com.yami.shop.service.UserLabelService;
import com.yami.shop.service.UserService;
import com.yami.shop.service.VipPackageService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import ma.glasnost.orika.MapperFacade;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * @author lgh on 2018/10/26.
 */
@RestController
@RequestMapping("/p/vip")
@Api(tags = "vip接口")
public class VipController {

    @Autowired
    private VipPackageService vipPackageService;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private VipPackageMapper vipPackageMapper;

    @Autowired
    private UserService userService;

    private final Integer VIP_UNLOCK_COUNT = 10;


    @GetMapping
    @ApiOperation(value = "获取Vip套餐", notes = "获取Vip套餐")
    public ResponseEntity<List<VipPackage>> page() {
        List<VipPackage> list = vipPackageService.list();
        return ResponseEntity.ok(list);
    }

    @PostMapping("receive")
    @ApiOperation(value = "领取VIP", notes = "领取VIP,优惠数量大于0时可以领取，领取的套餐是新人优惠套餐")
    public ResponseEntity<Void> receive() {
        String userId = SecurityUtils.getUser().getUserId();

        VipPackage p = vipPackageMapper.selectOne(new LambdaQueryWrapper<VipPackage>()//查询优惠VIP套餐
        .eq(VipPackage::getId,userService.getById(userId).getDiscount()));//根据Discount获取用户所领的vip套餐
        if(p == null){
            return ResponseEntity.ok().build();//没有此套餐
        }
        Date now = new Date();
        User user = new User();
        user.setUserId(userId);
        if (userService.getById(userId).getIsVip() == 0){
            user.setVipStartTime(now);
            user.setVipEndTime(DateUtil.offsetDay(now,p.getDayCount()));
        }else {//是VIP的话说明是续充
            Date endTime = userMapper.selectById(userId).getVipEndTime();
            user.setVipEndTime(DateUtil.offsetDay(endTime,p.getDayCount()));
        }
        user.setIsVip(1);
        user.setTodayUnlockSurplus(VIP_UNLOCK_COUNT);//剩余解锁次数
        user.setDiscount(0);//优惠设置为0
        userService.updateById(user);
        return ResponseEntity.ok().build();
    }

    @PostMapping
    @ApiOperation(value = "购买VIP", notes = "购买VIP")
    public ResponseEntity<Void> buy(@RequestBody VipBuyParam param) {
        VipPackage p = vipPackageService.getById(param.getPackageId());
        String userId = SecurityUtils.getUser().getUserId();
        Date now = new Date();
        /*if(userService.getById(userId).getIsVip() == 1){
            throw new YamiShopBindException("已经是VIP，无法购买VIP");
        }*/
        User user = new User();
        p.getDayCount();
        user.setUserId(userId);
        if (userService.getById(userId).getIsVip() == 0){
            user.setVipStartTime(now);
            user.setVipEndTime(DateUtil.offsetDay(now,p.getDayCount()));
        }else {//是VIP的话说明是续充
            Date endTime = userMapper.selectById(userId).getVipEndTime();
            user.setVipEndTime(DateUtil.offsetDay(endTime,p.getDayCount()));
        }
        user.setIsVip(1);
        user.setTodayUnlockSurplus(VIP_UNLOCK_COUNT);
        if(userService.getById(userId).getIsFirstVip() == 0){
            user.setIsFirstVip(1);
            if (userService.getById(userId).getUppInvitatioCode() != null && userService.getById(userId).getUppInvitatioCode().equals("")){
                //被邀请的朋友首次购买VIP，邀请人可以享受48小时内解密6个微信号时间和解密数量
                userMapper.uppCodeRepeatVip(userService.getById(userId).getUppInvitatioCode());
                if (userService.getById(userId).getSex().equals("M")){//当前用户是男生
                    if (userMapper.uppJudge(userService.getById(userId).getUppInvitatioCode()) != null){//上级用户性别不等于null
                        if (userMapper.uppJudge(userService.getById(userId).getUppInvitatioCode()).equals("F")){//如果上级是女生的话
                            //把rmb都反给女生
                            User user1 = userMapper.selectById(userId);//当前用户的信息
                            User user2 = userMapper.selectOne(new QueryWrapper<User>().eq("invitatio_code",user1.getUppInvitatioCode()));//上级用户信息
                            VipPackage vips = vipPackageMapper.selectOne(new QueryWrapper<VipPackage>().eq("id",param.getPackageId()));
                            user2.setWallet(user2.getWallet() + vips.getPrice());
                            userMapper.updateById(user2);
                        }

                    }
                }

            }
        }else if(userService.getById(userId).getIsFirstVip() == 1){
            if (now.before(userService.getById(userId).getVipEndTime())){
                //首次VIP续充
                user.setIsFirstVip(2);
            }
        }
        userService.updateById(user);
        return ResponseEntity.ok().build();
    }




}
